<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use app\model\VisitorInternet as InternetModel;
use app\middleware\CheckLogin;

class Internet extends BaseController
{

    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];
    
    /**
     * 显示线索数据列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        
        $endDate = $request->param('endDate');

        if(empty($startDate)){
            $startDate = date("Y-m-d H:i:s",strtotime("-30 day"));
        }else{
            $startDate = $request->param('startDate');
        }

        if(empty($endDate)){
            $endDate = date("Y-m-d H:i:s",time());
        }else{
            $endDate = $request->param('endDate');
        }

        $visitorData = InternetModel::whereTime('create_date','between',[$startDate,$endDate])->order('create_date', 'desc')->select();
        View::assign('visitorData',$visitorData);

        return view('index');
        // dump($startDate,$endDate);
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function analysis()
    {
        
        return view('analysis');
    }


    /**
     * 返回日期编号及对比数据的json
     *
     * @return \think\Response
     */
    public function analysisJson(Request $request)
    {
        //根据模式调用API输入始末时间及日期标识
        $daterange = $request->param('daterange');

        //获取始末日期
        $date = DateInterval($daterange);

        //主趋势线图部分
        /////////////////////////////////////////////////////////////////
        $thisStart = $date['thisStart'];
        $lastStart = $date['lastStart'];

        for($x=0;$x<$date['maxDays'];$x++){

            //日期赋值
            $line_data[$x]['day'] = date('d',$thisStart)."日";

            //本期数据
            $thisData = InternetModel::where('create_date',date('Y-m-d H:i:s',$thisStart))->find();
            if(!empty($thisData)){
                $line_data[$x]['thisNumber'] =  $thisData['autohome_count'] + $thisData['yiche_count'] + $thisData['other_count'];
            }else{
                $line_data[$x]['thisNumber'] = 0;
            }

            //上期数据
            $lastData = InternetModel::where('create_date',date('Y-m-d H:i:s',$lastStart))->find();
            if(!empty($lastData)){
                $line_data[$x]['lastNumber'] =  $lastData['autohome_count'] + $lastData['yiche_count'] + $lastData['other_count'];
            }else{
                $line_data[$x]['lastNumber'] = 0;
            }
            
            //本周期日期增加
            $thisStart = strtotime("+1day",$thisStart);//加一天
            $thisData = array();

            //上周期日期增加
            $lastStart = strtotime("+1day",$lastStart);//加一天
            $lastData = array();
            
        }

        $data['line_data'] = $line_data;

        //饼图部分
        /////////////////////////////////////////////////////////////////////////

        //统计区间数据
        $statisticsData = $this->statistics($date);

        // 本期数据
        $data['total_count'] = $statisticsData['total_count'];
        $data['autohome_count'] = $statisticsData['autohome_count'];
        $data['yiche_count'] = $statisticsData['yiche_count'];

        //  上期数据
        if($statisticsData['last_total_count'] != 0){
            $data['total_count_growth_rate'] = intval(($statisticsData['total_count'] - $statisticsData['last_total_count']) / $statisticsData['last_total_count']  *100).'%';
        }else{
            $data['total_count_growth_rate'] = '无';
        }
        if($statisticsData['last_autohome_count'] != 0){
            $data['autohome_count_growth_rate'] = intval(($statisticsData['autohome_count'] - $statisticsData['last_autohome_count']) / $statisticsData['last_autohome_count']  *100).'%';
        }else{
            $data['autohome_count_growth_rate'] =  '无';
        }
        if($statisticsData['last_yiche_count'] != 0){
            $data['yiche_count_growth_rate'] = intval(($statisticsData['yiche_count'] - $statisticsData['last_yiche_count']) / $statisticsData['last_yiche_count']  *100).'%';
        }else{
            $data['yiche_count_growth_rate'] = '无';
        }
        

        //渠道数据
        if(!empty($statisticsData['total_count'])){
            $autohomeRadio = sprintf("%.2f",$statisticsData['autohome_count'] / $statisticsData['total_count'] * 100);
            $yicheRadio = sprintf("%.2f",$statisticsData['yiche_count'] / $statisticsData['total_count'] * 100);
            $otherRadio = sprintf("%.2f",$statisticsData['other_count'] / $statisticsData['total_count'] * 100);
        }else{
            $autohomeRadio = 0;
            $yicheRadio = 0;
            $otherRadio = 0;
        }
        $channelRatio['label']  = array('汽车之家 '.$autohomeRadio."%",'易车网 '.$yicheRadio."%",'其它 '.$otherRadio."%");
        $channelRatio['data']  = array($statisticsData['autohome_count'],$statisticsData['yiche_count'],$statisticsData['other_count']);
        $data['channelRatio'] = $channelRatio;

        //线索有效率
        if(!empty($statisticsData['total_count'])){
            $validRadio = sprintf("%.2f",$statisticsData['total_valid'] / $statisticsData['total_count'] * 100);
            $invalid = $statisticsData['total_count'] - $statisticsData['total_valid'];
            $invalidRadio = sprintf("%.2f", $invalid / $statisticsData['total_count'] * 100);
        }else{
            $validRadio = 0;
            $invalidRadio = 0;
        }
        $validRatio['label']  = array('有效线索 '.$validRadio."%",'无效线索 '.$invalidRadio."%");
        $validRatio['data']  = array($statisticsData['total_valid'],$statisticsData['total_count'] - $statisticsData['total_valid']);
        $data['validRatio'] = $validRatio;

        //有效线索邀约率
        if(!empty($statisticsData['total_valid'])){
            $inviteRadio = sprintf("%.2f",$statisticsData['total_invite'] / $statisticsData['total_valid'] * 100);
            $noInvite= $statisticsData['total_valid'] - $statisticsData['total_invite'];
            $noInviteRadio = sprintf("%.2f", $noInvite / $statisticsData['total_valid'] * 100);
        }else{
            $inviteRadio = 0;
            $noInviteRadio = 0;
        }
        $TotalValidRatio['label']  = array('成功率 '.$inviteRadio."%",'失败率 '.$noInviteRadio."%");
        $TotalValidRatio['data']  = array($statisticsData['total_invite'],$statisticsData['total_valid'] - $statisticsData['total_invite']);
        $data['inviteRatio'] = $TotalValidRatio;

        //总线索成交率
        if(!empty($statisticsData['total_order'])){
            $dealRadio = sprintf("%.2f",$statisticsData['total_order'] / $statisticsData['total_count'] * 100);
            $noDeal= $statisticsData['total_count'] - $statisticsData['total_order'];
        }else{
            $dealRadio = 0;
            $noDeal = 0;
        }
        $TotalDealRadio['label']  = array('成交率 '.$dealRadio."%",'待成交 '.$noDeal."批");
        $TotalDealRadio['data']  = array($statisticsData['total_order'],$statisticsData['total_count'] - $statisticsData['total_order']);
        $data['dealRatio'] = $TotalDealRadio;

        // dump($statisticsData);
        return json($data); 
        
    }

    /**
     * 显示编辑日报单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function log($id){

        //获取数据
        $todayData = InternetModel::find($id);

         //当日日期
        $today = date("Y-m-d",strtotime($todayData['create_date']));
        $data['toDayDate'] =  $today;

        // 本月第一天
        $date['thisStart'] = strtotime("first day of this month 00:00:00",strtotime($todayData['create_date']));
        // 统计截止时间
        $date['thisEnd'] = strtotime(date("Y-m-d 23:59:59",strtotime($todayData['create_date'])));
        //上周期开始
        $date['lastStart'] = strtotime("first day of last month 00:00:00",strtotime($todayData['create_date']));
        //本周期开始
        $date['lastEnd'] = strtotime('-1 month',$date['thisEnd']);

        // //获取本期始末时间
        $log_data = $this->statistics($date);

        //当日数据
        $data['autohome_count'] = $todayData['autohome_count'];
        $data['yiche_count'] = $todayData['yiche_count'];
        $data['other_count'] = $todayData['other_count'];

        $data['autohome_valid'] = $todayData['autohome_valid'];
        $data['yiche_valid'] = $todayData['yiche_valid'];
        $data['other_valid'] = $todayData['other_valid'];

        $data['autohome_invite'] = $todayData['autohome_invite'];
        $data['yiche_invite'] = $todayData['yiche_invite'];
        $data['other_invite'] = $todayData['other_invite'];

        $data['autohome_order'] = $todayData['autohome_order'];
        $data['yiche_order'] = $todayData['yiche_order'];
        $data['other_order'] = $todayData['other_order'];

        // 本月总线索
        $data['total_count'] = $log_data['total_count'];

        //本月总有效线索
        $data['total_valid'] = $log_data['total_valid'];

        //本月总邀约
        $data['total_invite'] = $log_data['total_invite'];

        //本月总订单
        $data['total_order'] = $log_data['total_order'];

        //本月总交车
        $data['total_delivery'] = $log_data['total_delivery'];

        // //总线索有效率
        if($data['total_count'] != 0 ){
            $data['countValidRate'] = sprintf("%.2f",$data['total_valid'] / $data['total_count'] * 100);
        }else{
            $data['countValidRate'] = 0;
        }

        //有效线索邀约率
        if($data['total_valid'] != 0){
            $data['inviteRate'] = sprintf("%.2f",$data['total_invite'] / $data['total_valid'] * 100);
        }else{
            $data['inviteRate'] = 0;
        }

        //总线索成交率
        if($data['total_count'] != 0){
            $data['orderRate'] = sprintf("%.2f",$data['total_order'] / $data['total_count'] * 100);
        }else{
            $data['orderRate'] = 0;
        }
        
        View::assign('data',$data);

        return view('log');

    }


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //渲染页面
        return view('create'); 
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $data = $request->param();
        $result = InternetModel::create($data);//调用create方法写入数据库

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //获取此前数据
        $data = InternetModel::where('id',$id)->find();
        View::assign('data',$data);

        return view('read'); 
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //获取此前数据
        $data = InternetModel::where('id',$id)->find();
        View::assign('data',$data);

        return view('edit');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = request()->param();
        $result = InternetModel::update($data);//调用create方法写入数据库
        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //删除
        $user = InternetModel::find($id);//删除id号
        $result = $user->delete();//确认删除结果，返回布尔值
        if($result){
            return "ok";//成功则返回OK
        }else{
            return "false";//失败则返回false
        }
    }
    
    //私有函数，返回网销数据统计结果，输入起时间及止时间
    private function statistics($date)
    {
        //本期始末日期
        $data['startDate'] = date("Y-m-d H:i:s",$date['thisStart']);
        $data['endDate'] = date("Y-m-d H:i:s",$date['thisEnd']);
        $start = $date['thisStart'];
        $end = $date['thisEnd'];
        $lastStart = $date['lastStart'];
        $lastEnd = $date['lastEnd'];

        //本周期总线索
        $data['autohome_count'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum('autohome_count');
        $data['yiche_count'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("yiche_count");
        $data['other_count'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("other_count");
        $data['total_count'] = $data['autohome_count'] + $data['yiche_count'] + $data['other_count'];

        //上周期总线索
        $data['last_autohome_count'] = InternetModel::whereTime('create_date',"between",[$lastStart,$lastEnd])->sum('autohome_count');
        $data['last_yiche_count'] = InternetModel::whereTime('create_date',"between",[$lastStart,$lastEnd])->sum("yiche_count");
        $data['last_other_count'] = InternetModel::whereTime('create_date',"between",[$lastStart,$lastEnd])->sum("other_count");
        $data['last_total_count'] = $data['last_autohome_count'] + $data['last_yiche_count'] + $data['last_other_count'];

        //本周期总有效线索
        $data['autohome_valid'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum('autohome_valid');
        $data['yiche_valid'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("yiche_valid");
        $data['other_valid'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("other_valid");
        $data['total_valid'] = $data['autohome_valid'] + $data['yiche_valid'] + $data['other_valid'];

        //本周期总邀约
        $data['autohome_invite'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum('autohome_invite');
        $data['yiche_invite'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("yiche_invite");
        $data['other_invite'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("other_invite");
        $data['total_invite'] = $data['autohome_invite'] + $data['yiche_invite'] + $data['other_invite'];

        //本周期总订单
        $data['autohome_order'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum('autohome_order');
        $data['yiche_order'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("yiche_order");
        $data['other_order'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum("other_order");
        $data['total_order'] = $data['autohome_order'] + $data['yiche_order'] + $data['other_order'];

        //本周期总交车
        $data['total_delivery'] = InternetModel::whereTime('create_date',"between",[$start,$end])->sum('today_delivery');

        return $data;

    }
}
